package com.zl.easybuy.service.impl;

import com.zl.easybuy.exc.EasyBuyExc;
import com.zl.easybuy.mapper.ProductMapper;
import com.zl.easybuy.mapper.UserMapper;
import com.zl.easybuy.pojo.Product;
import com.zl.easybuy.service.ShoppingCartService;
import com.zl.easybuy.util.CartItem;
import com.zl.easybuy.util.SessionUtil;
import com.zl.easybuy.util.ShoppingCart;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    ProductMapper productMapper;
    @Override
    public boolean addShoppingCart(Integer entityId,Integer quantity) throws EasyBuyExc {
        Product product=productMapper.findById(entityId);
        if(product.getStock()<quantity){
            throw new EasyBuyExc("库存不足");
        }
        ShoppingCart cart = SessionUtil.getCurrentCart();
        if(cart==null){
            cart=new ShoppingCart();
            SessionUtil.setCartInSession(cart);
        }
        //遍历购物车
        if(!CollectionUtils.isEmpty(cart.getItems())){
            for(CartItem cartItem:cart.getItems()){
                //比较添加后的数量和库存数量
                if(cartItem.getProduct().getId().intValue()==product.getId().intValue()){
                    if((quantity+cartItem.getQuantity())>product.getStock()){
                        return false;
                    }
                    cartItem.setQuantity(quantity+cartItem.getQuantity());
                    return true;
                }
            }
        }
        CartItem cartItem=new CartItem();
        cartItem.setQuantity(quantity);
        cartItem.setProduct(product);
        cart.getItems().add(cartItem);
        return true;
    }

    @Override
    public boolean modQuantity(Integer entityId, Integer quantity) {
        Product product=new Product();
        product=productMapper.findById(entityId);
        if(product.getStock()<quantity){
            return false;
        }
        ShoppingCart cart = SessionUtil.getCurrentCart();
        //遍历购物车
        if(!CollectionUtils.isEmpty(cart.getItems())){
            for(CartItem cartItem:cart.getItems()){
                //比较添加后的数量和库存数量
                if(cartItem.getProduct().getId().intValue()==product.getId().intValue()){
                    if(quantity==0){
                        cart.getItems().remove(cartItem);
                        return true;
                    }
                    if(quantity>product.getStock()){
                        return false;
                    }
                    cartItem.setQuantity(quantity);
                    return true;
                }
            }
        }
        return true;
    }
}
